package love.lemoncat.websocket;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import love.lemoncat.service.MockDevService;
import love.lemoncat.websocket.msg.RequestMsg;
import love.lemoncat.websocket.msg.ResponseMsg;

import java.util.HashSet;
import java.util.Set;

@Slf4j
public class ClientHolder {

    private Channel channel;
    // 单主题【设备id号】
    private String devNo = null;
    // 多主题【多设备id号，暂时用不上】
    private Set<String> devNos = new HashSet<String>();

    public ClientHolder(Channel channel) {
        this.channel = channel;
    }

    public boolean handable(ResponseMsg responseMsg) {
        String devNo = responseMsg.getDevNo();
        if (devNo == null) {
            return false;
        }
        return devNo.equals(this.devNo);
    }

    public boolean handable(String devNo) {
        if (devNo == null) {
            return false;
        }
        return devNo.equals(this.devNo);
    }

    public void handleRequest(RequestMsg requestMsg, MockDevService mockService) {
        this.devNo = requestMsg.getDevNo();
        if (this.devNo == null) {
            this.handleResponseError("topic不能为空");
            return;
        }
        ResponseMsg responseMsg = new ResponseMsg();
        responseMsg.setDevNo(this.devNo);
        responseMsg.setDataType(requestMsg.getDataType());
        switch (requestMsg.getDataType()) {
            case PARAM:
                // 查询设备信息
                String baseInfo = mockService.get(requestMsg);
                responseMsg.setData(baseInfo);
                break;
            case LOG:
                break;
            case STATUS:
                break;
        }
        // 返回处理结果
        this.handleResponse(responseMsg);
    }

    public void handleResponse(ResponseMsg resp) {
        // 当前激活设备页面一致则推送
        if (this.handable(resp)) {
            TextWebSocketFrame textWebSocketFrame = null;
            try {
                textWebSocketFrame = resp.encodeTextFrame();
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.channel.writeAndFlush(textWebSocketFrame);
        }
    }

    public void handleResponseError(String errorInfo) {
        ResponseMsg resp = new ResponseMsg();
        resp.setSuccess(false);
        resp.setData(errorInfo);
        // 推送
        TextWebSocketFrame textWebSocketFrame = null;
        try {
            textWebSocketFrame = resp.encodeTextFrame();
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.channel.writeAndFlush(textWebSocketFrame);
    }
}
